﻿using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using JiaBao.Core;
using JiaBao.Services.AuctionService;
using JiaBao.Services.CustomerService;
using JiaBao.Services.ExcelService;
using JiaBao.Services.LogService;
using JiaBao.Services.StoreService;
using JiaBao.WPF.Dialog;
using JiaBao.WPF.Framework.Controls;
using System.Windows.Data;

namespace JiaBao.WPF.Customer
{


    /// <summary>
    /// uc_Customer.xaml 的交互逻辑
    /// </summary>
    public partial class p_Customer : Page
    {
        /// <summary>
        /// 当前页面线程
        /// </summary>
        Dispatcher Mainthread = Dispatcher.CurrentDispatcher;
        private readonly ICustomerService _customerService;

        private readonly IStoreService _storeService;
        private readonly IAuctionService _auctionService;
        private readonly IExcelService _excelService;

        #region Ctor

        public p_Customer(ICustomerService customerService, IStoreService storeService, IAuctionService auctionService, IExcelService excelService)
        {
            InitializeComponent();

            try
            {
                _customerService = customerService;
                _storeService = storeService;
                this._auctionService = auctionService;
                _excelService = excelService;
                cmb_Find.Items.Add("姓名");
                cmb_Find.Items.Add("手机");
                cmb_Find.Items.Add("证件号码");
                cmb_Find.SelectedIndex = 0;


                cmb_AucH.Items.Add(new ComboBoxItem() { Content = "[全部]", Tag = -100 });
                cmb_Auction.Items.Add(new ComboBoxItem() { Content = "[全部]", Tag = -100 });
                foreach (DataRow r in _auctionService.GetAll().Rows)
                {
                    lt_Update.Items.Add(new ListBoxItemEx() { Content = r[0].ToString(), ItemData = (int)r[1] });
                    cmb_Auction.Items.Add(new ComboBoxItem() { Content = r[0].ToString(), Tag = (int)r[1] });
                    cmb_AucH.Items.Add(new ComboBoxItem() { Content = r[0].ToString(), Tag = (int)r[1] });
                }

                #region 表格右键

                //表格右键菜单
                var menu = new ContextMenu();

                //复制客户标识
                var mi = new MenuItem()
                {
                    Header = "复制客户标识"

                };
                mi.Click += (object sender, RoutedEventArgs e) =>
                            {
                                if (!(dg_Main.CurrentItem is DataRowView item)) return;


                                var bs = item["客户标识"];
                                Clipboard.SetDataObject(bs.ToString());
                                dg_Main.Tag = item["姓名"];

                            };


                //合并客户
                var mi2 = new MenuItem()
                {
                    Header = "合并客户"

                };
                mi2.Click += (object sender, RoutedEventArgs e) =>
                                {
                                    if (!(dg_Main.CurrentItem is DataRowView item)) return;

                                    var bs = item["客户标识"];

                                    string newbs = (string)Clipboard.GetData(DataFormats.Text);

                                    if (32 == newbs.Length && bs.ToString() != newbs)
                                    {
                                        txt_UpdateBS.Text = newbs;
                                        lab_UpdateBS.Content = "确认合并 [" + item["姓名"].ToString() + "] 到[" + dg_Main.Tag.ToString() + "]";
                                    }
                                    else
                                    {
                                        lab_UpdateBS.Content = "请填写合并客户标识";
                                    }

                                    lab_UpdateBS.Tag = bs;
                                    SetEnabled(false);

                                    //赋值

                                    g_UpdateBS.Visibility = Visibility.Visible;

                                };

                menu.Items.Add(mi);
                menu.Items.Add(mi2);
                dg_Main.ContextMenu = menu;

                #endregion
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        bool first = true;
        /// <summary>
        /// 刷新表格
        /// </summary>
        private void RefreshCustomer(int aucid = -200)
        {
            try
            {
                if (-200 == aucid)
                {
                    var si = cmb_Auction.SelectedItem as ComboBoxItem;
                    if (null == si) return;
                    aucid = (int)si.Tag;
                }
                bool? isbuyer;
                if (true == ck_Buyer.IsChecked)
                    if (true == ck_Saler.IsChecked)
                        isbuyer = null;
                    else
                        isbuyer = true;
                else
                    if (true == ck_Saler.IsChecked)
                    isbuyer = false;
                else
                    isbuyer = null;


                var dt = _customerService.GetCustomersByAucIdAndBuyerOrSaler(aucid, isbuyer);
                dg_Main.ItemsSource = dt.DefaultView;

                dg_Main.IsReadOnly = true;
                dg_Main.Column("Id").Visibility = Visibility.Hidden;
                dg_Main.Column("客户标识").Width = 100;
                dg_Main.Column("委托总额").Visibility = Visibility.Hidden;
                dg_Main.Column("购买总额").Visibility = Visibility.Hidden;

                if (!first) return;

                List<string> cols = new List<string>();
                foreach (var col in dg_Main.Columns.Where(x => x.Visibility == Visibility.Visible))
                {
                    cols.Add(col.Header.ToString());
                }

                C_Edit.Ini(cols);
                first = false;
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }



        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_Refresh_Click(object sender, RoutedEventArgs e)
        {


            try
            {
                var loadingDialog = new LoadingDialog();

                var result = await DialogHost.Show(loadingDialog, "Dialog", delegate (object sender1, DialogOpenedEventArgs args)
               {


                   ThreadStart start = delegate ()
                   {

                       Thread.Sleep(100);
                       Mainthread.BeginInvoke((Action)delegate ()// 异步更新界面
                       {
                           RefreshCustomer();
                           args.Session.Close(false);
                       });

                   };

                   new Thread(start).Start(); // 启动线程

               });


            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }




        #region 关联变化

        /// <summary>
        /// 换行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dg_Main_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                TabselectionChanged(tab_Cus.SelectedIndex);
                DataRowView item = (DataRowView)dg_Main.SelectedItem;
                if (null != item)
                {
                    lab_Jtdh.Content = String.Format("{0:N}", string.IsNullOrEmpty(item["购买总额"].ToString()) ? 0 : item["购买总额"]);
                    lab_Saler.Content = String.Format("{0:N}", string.IsNullOrEmpty(item["委托总额"].ToString()) ? 0 : item["委托总额"]);
                }
                else
                {

                    lab_Jtdh.Content = "购买总额:0.00";
                    lab_Saler.Content = "委托总数0.00:";
                }
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }


        }

        /// <summary>
        /// 换页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tab_Cus_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabselectionChanged(tab_Cus.SelectedIndex);

        }

        /// <summary>
        /// 关联变化
        /// </summary>
        /// <param name="index"></param>
        private void TabselectionChanged(int index)
        {
            try
            {
                var selectItem = dg_Main.SelectedItem as DataRowView;

                if (null == selectItem) return;
                var z = selectItem["客户标识"].ToString();

                int aucid = -100;
                var si = cmb_AucH.SelectedItem as ComboBoxItem;
                if (null != si)
                    aucid = (int)si.Tag;

                DataTable dt = null;
                DataGridEx dg = null;



                switch (index)
                {
                    case 0:
                        dt = _storeService.GetByJtdjAndAucId(z, aucid);
                        dg = dg_Jtdj;
                        dg.Columns.Clear();
                        dg.ItemsSource = dt.DefaultView;

                        //定义ZT按钮
                        DataGridTemplateColumn column = new DataGridTemplateColumn()
                        {
                            Header = "ZT",
                            Width = 100
                        };

                        DataTemplate temp = new DataTemplate();

                        //生成Grid
                        FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid));

                        //生成Button
                        FrameworkElementFactory button = new FrameworkElementFactory(typeof(Button));
                        button.SetValue(Button.HeightProperty, 25.00);

                        button.SetValue(Button.ContentProperty, "ZT");

                        button.AddHandler(Button.ClickEvent, new RoutedEventHandler(
                            (object sender, RoutedEventArgs e) =>
                            {
                                var item = dg_Jtdj.CurrentItem as DataRowView;

                                if (null == item)
                                    return;

                                if (!string.IsNullOrEmpty(item["买家结算状况"].ToString()))
                                    return;

                                if (false == ck_ZT.IsChecked)
                                    if (MessageBox.Show("确认更改[" + item["图录号"].ToString() + "]为ZT", "提示", MessageBoxButton.YesNo) == MessageBoxResult.No)
                                        return;

                                var auc = (int)item["拍卖会id"];
                                var tol = (int)item["图录号"];
                                var r = _storeService.UpdateZT(auc, tol);
                                if (1 == r)
                                    item["买家结算状况"] = "ZT";
                                else
                                    MessageBox.Show("更新数量大于1");

                                ;
                            }));

                        grid.AppendChild(button);

                        temp.VisualTree = grid;
                        column.CellTemplate = temp;

                        dg.Columns.Add(column);
                        break;

                    case 1:
                        dt = _storeService.GetByHtAndAucId(z, aucid);
                        dg = dg_Saler;
                        dg.ItemsSource = dt.DefaultView;
                        break;

                    default:
                        return;
                }
                dg.Column("拍卖会id").Visibility = Visibility.Hidden;
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        /// <summary>
        /// 定位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Find_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var find = txt_Find.Text.Trim();
                if (string.IsNullOrEmpty(find))
                    return;
                //当前位置向下
                for (int i = dg_Main.SelectedIndex + 1; i < dg_Main.Items.Count; i++)
                {
                    var selectItem = dg_Main.Items[i] as DataRowView;
                    if (null == selectItem)
                        break;
                    var s = selectItem[cmb_Find.Text].ToString();
                    if (s.Contains(find))
                    {
                        dg_Main.SelectedItem = selectItem;
                        dg_Main.CurrentItem = selectItem;
                        dg_Main.ScrollIntoView(selectItem);
                        return;
                    }

                }
                //从0 到当前位置
                for (int i = 0; i < dg_Main.SelectedIndex; i++)
                {
                    var selectItem = dg_Main.Items[i] as DataRowView;
                    if (null == selectItem)
                        break;
                    var s = selectItem[cmb_Find.Text].ToString();
                    if (s.Contains(find))
                    {
                        dg_Main.SelectedItem = selectItem;
                        dg_Main.CurrentItem = selectItem;
                        dg_Main.ScrollIntoView(selectItem);
                        return;
                    }
                }
                dg_Main.Focus();
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }

        }

        #region 编辑

        /// <summary>
        /// 双击编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dg_Main_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

            try
            {
                SetEnabled(false);

                DataRowView selectItem = dg_Main.SelectedItem as DataRowView;
                Dictionary<string, string> d = new Dictionary<string, string>();

                foreach (var col in dg_Main.Columns.Where(x => x.Visibility == Visibility.Visible))
                {
                    var k = col.Header.ToString();
                    var v = selectItem[col.DisplayIndex];
                    d.Add(k, null == v ? "" : v.ToString());
                }
                C_Edit.Show(d);
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 关闭编辑
        /// </summary>
        /// <param name="data"></param>
        private void C_Edit_Close(Dictionary<string, string> data)
        {
            SetEnabled(true);

        }

        /// <summary>
        /// 编辑修改
        /// </summary>
        /// <param name="data"></param>
        private void C_Edit_Ok(Dictionary<string, string> data)
        {
            try
            {
                if (null == data) goto end;

                DataRowView selectItem = dg_Main.SelectedItem as DataRowView;
                if (null == selectItem) goto end;

                var z = selectItem["客户标识"];
                if (null == z) goto end;

                List<SqlParameter> parameter = new List<SqlParameter>();
                string sql = string.Empty;

                foreach (var d in data)
                {
                    selectItem[d.Key] = d.Value;
                    sql += "," + d.Key + "=@" + d.Key;
                    parameter.Add(new SqlParameter(d.Key, d.Value));
                }


                if (sql.Length < 1) goto end;

                sql = sql.Substring(1);

                sql = "update Customer_Z set " + sql + " where 客户标识 =@客户标识 ";
                parameter.Add(new SqlParameter("客户标识", z));
                _customerService.ExecuteNonQuery(sql, parameter.ToArray());



            end:
                SetEnabled(true);
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        #endregion


        /// <summary>
        /// 锁定控件
        /// </summary>
        /// <param name="enabled"></param>
        private void SetEnabled(bool enabled)
        {
            try
            {
                dg_Main.IsEnabled = enabled;
                g_Operational.IsEnabled = enabled;
                g_Tip.IsEnabled = enabled;
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }


        #region 更新客户资料

        /// <summary>
        /// 打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Update_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SetEnabled(false);

                //默认近3届
                for (int i = 0; i < 3; i++)
                {
                    (lt_Update.Items[i] as ListBoxItemEx).IsChecked = true;
                }
                g_Update.Visibility = Visibility.Visible;

            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }

        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Update_Close_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                g_Update.Visibility = Visibility.Hidden;
                foreach (ListBoxItemEx i in lt_Update.Items)
                {
                    var s = i.IsChecked;
                    i.IsChecked = false;
                }

                SetEnabled(true);
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 更新买卖家 生日 总额 等资料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Update_Ok_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var s = "";
                foreach (ListBoxItemEx i in lt_Update.Items)
                    if (true == i.IsChecked)
                        s += "," + i.ItemData;

                if (s.Length < 1) return;
                s = s.Substring(1);

                _customerService.Update();
                _customerService.UpdateSum(s);
                RefreshCustomer();

                btn_Update_Close_Click(null, null);
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }


        }

        #endregion

        private void btn_ToExcel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var p = CommonHelper.FolderBrowserDialog();

                if (null == p) return;

                p = Path.Combine(p, "客户资料" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls");

                if (null == dg_Main.ItemsSource) return;
                var dt = (dg_Main.ItemsSource as DataView).ToTable();
                if (0 == dt.Rows.Count) return;


                byte[] excel = _excelService.DataTableToExcel(dt);


                if (!File.Exists(p))
                {
                    FileStream fs = new FileStream(p, FileMode.CreateNew);
                    fs.Write(excel, 0, excel.Length);
                    fs.Close();

                }
                MessageBox.Show("导出完成");
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }



        #region 更改客户标识

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_UpdateBS_Close_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                g_UpdateBS.Visibility = Visibility.Hidden;
                txt_UpdateBS.Text = "";
                lab_UpdateBS.Content = "";

                SetEnabled(true);
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_UpdateBS_Ok_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var oldbs = lab_UpdateBS.Tag.ToString();
                var newbs = txt_UpdateBS.Text.ToString();

                if (newbs.Length != 32) return;

                if (oldbs == newbs) return;

                _customerService.UpdateKHBS(oldbs, newbs);

                btn_UpdateBS_Close_Click(null, null);

            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        private void cmb_Auction_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {


                var si = cmb_Auction.SelectedItem as ComboBoxItem;
                if (null == si)
                    return;
                RefreshCustomer((int)si.Tag);
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }



        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            RefreshCustomer();
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            RefreshCustomer();
        }

        private void cmb_AucH_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabselectionChanged(tab_Cus.SelectedIndex);
        }

        private void dg_Jtdj_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
        }
    }
}
